﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ReportFlat.Common;
using ReportFlat.DataAccess;
using System.Collections;


namespace ReportFlat.Web.server.report
{
    /// <summary>
    /// Supplier 的摘要说明
    /// </summary>
    public class Report : BaseHandler
    {
        [UseDB]
        public void IsTeamLeader()
        {
            if (GMLogin.isAdminUser() || GMLogin.isRole(11))
            {
                jsonResult = JSONHelper.SuccessJson;
                return;
            }
            t_dept_user dUser = dao.Get<t_dept_user>("FUserName="+Request["UserName"].wrap());
            if (dUser!=null)
            {
                t_dept dept = dao.Get<t_dept>(dUser.FDeptID);
                if (dept != null && dept.FLeader == GMLogin.User.FRealName)
                {
                    jsonResult = JSONHelper.SuccessJson;
                    return;
                }
            }
            jsonResult = JSONHelper.ToErroJson("您没有权限");
        }
        /// <summary>
        /// 总监报表
        /// </summary>
        [UseDB]
        public void GetTopReport()
        {
            IList<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
            IList<Dictionary<string, object>> reports = GetTeamReportInner();
            IList leaders = dao.QueryBySql("select distinct FUpLeader from t_dept where FUpLeader<>'' and FUpLeader is not null");
            foreach (String leader in leaders)
            {
                //只能看自己的数据
                /*
                if (!GMLogin.isAdminUser() && !GMLogin.isRole(11))
                {
                    if (leader != GMLogin.User.FRealName)
                    {
                        continue;
                    }
                }
                 */
                Dictionary<string, object> item = new Dictionary<string, object>();
                result.Add(item);
                item["UserName"] = leader;
                item["Count0"] = 0;
                item["Count1"] = 0;
                item["Count2"] = 0;
                item["Count3"] = 0;
                item["Count4"] = 0;
                IList<t_dept> depts = dao.GetList<t_dept>("FUpLeader=" + leader.wrap());
                //TODO：修改为LINQ
                foreach (var dept in depts)
                {
                    foreach (var report in reports)
                    {
                        if (dept.FName == report["UserName"].ToString())
                        {
                            item["Count0"] = Convert.ToInt32(item["Count0"]) + Convert.ToInt32(report["Count0"]);
                            item["Count1"] = Convert.ToInt32(item["Count1"]) + Convert.ToInt32(report["Count1"]);
                            item["Count2"] = Convert.ToInt32(item["Count2"]) + Convert.ToInt32(report["Count2"]);
                            item["Count3"] = Convert.ToInt32(item["Count3"]) + Convert.ToInt32(report["Count3"]);
                            item["Count4"] = Convert.ToInt32(item["Count4"]) + Convert.ToInt32(report["Count4"]);
                            break;
                        }
                    }
                }
            }
            jsonResult = JSONHelper.ToSucJson("data", result);
        }

        /// <summary>
        /// 团队报表
        /// </summary>
        [UseDB]
        public void GetTeamReport()
        {
            jsonResult = JSONHelper.ToSucJson("data", GetTeamReportInner());
        }

        /// <summary>
        /// 个人报表
        /// </summary>
        [UseDB]
        public void GetAllReport()
        {
            jsonResult = JSONHelper.ToSucJson("data", GetAllReportInner(false));
        }

        [UseDB]
        public void Test()
        {
            IList<t_user> user = dao.GetList<t_user>("FIF=1");
            jsonResult = JSONHelper.SuccessJson;
        }

        private IList<Dictionary<string, object>> GetTeamReportInner()
        {
            IList<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
            IList<Dictionary<string, object>> reports = GetAllReportInner(true);
            string where = "1=1";
            string topName = JSONHelper.GetString(Request["oWhere"], "topName");
            if (!String.IsNullOrEmpty(topName))
            {
                where = "FUpLeader=" + topName.wrap();
            }
            IList<t_dept> depts = dao.GetList<t_dept>(where);
            foreach (var dept in depts)
            {
                //只能看自己的数据
                /*
                if (!GMLogin.isAdminUser() && !GMLogin.isRole(11) && string.IsNullOrEmpty(topName) && !isTop)
                {
                    if (dept.FLeader != GMLogin.User.FRealName && dept.FUpLeader != GMLogin.User.FRealName)
                    {
                        continue;
                    }
                }
                 */
                Dictionary<string, object> item = new Dictionary<string, object>();
                result.Add(item);
                item["UserName"] = dept.FName;
                item["Count0"] = 0;
                item["Count1"] = 0;
                item["Count2"] = 0;
                item["Count3"] = 0;
                item["Count4"] = 0;
                IList<t_dept_user> deptUser = dao.GetList<t_dept_user>("FDeptID=" + dept.FID);
                //TODO：修改为LINQ
                foreach (var user in deptUser)
                {
                    foreach (var report in reports)
                    {
                        if (user.FUserName == report["UserName"].ToString())
                        {
                            item["Count0"] = Convert.ToInt32(item["Count0"]) + Convert.ToInt32(report["Count0"]);
                            item["Count1"] = Convert.ToInt32(item["Count1"]) + Convert.ToInt32(report["Count1"]);
                            item["Count2"] = Convert.ToInt32(item["Count2"]) + Convert.ToInt32(report["Count2"]);
                            item["Count3"] = Convert.ToInt32(item["Count3"]) + Convert.ToInt32(report["Count3"]);
                            item["Count4"] = Convert.ToInt32(item["Count4"]) + Convert.ToInt32(report["Count4"]);
                            break;
                        }
                    }
                }
            }
            return result;
        }

        private IList<Dictionary<string, object>> GetAllReportInner(bool isTeamCall)
        {
            IList<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
            string sqlUser = "SELECT DISTINCT FRealName FROM t_user WHERE FID>0 AND FRealName IS NOT NULL AND FRealName<>'' and FRealName not like '%,%'";
            string uWhere = Request["where"];
            if (!String.IsNullOrEmpty(uWhere) && uWhere.IndexOf("FRealName") >= 0)
            {
                //去掉时间部分
                //时间太难搞了，特殊处理一下吧
                //TODO：有空再使用remote=true实现
                int pos = uWhere.IndexOf("FRealName");
                uWhere = uWhere.Substring(pos);
                sqlUser = sqlUser.and(uWhere);
            }
            string teamName = JSONHelper.GetString(Request["oWhere"], "teamName");
            if (!isTeamCall)
            {
                if (String.IsNullOrEmpty(teamName))
                {
                    t_dept dept = dao.Get<t_dept>("FLeader=" + GMLogin.User.FRealName.wrap());
                    if (dept != null)
                    {
                        teamName = dept.FName;
                    }
                }
                if (!String.IsNullOrEmpty(teamName))
                {
                    t_dept dept = dao.Get<t_dept>("FName=" + teamName.wrap());
                    if (dept != null)
                    {
                        IList<t_dept_user> deptUser = dao.GetList<t_dept_user>("FDeptID=" + dept.FID);
                        string inStr2 = "";
                        foreach (t_dept_user user in deptUser)
                        {
                            if (inStr2 != "")
                            {
                                inStr2 += ",";
                            }
                            inStr2 += "'" + user.FUserName + "'";
                        }
                        sqlUser = sqlUser.and(" FRealName in(" + inStr2 + ")");
                    }
                }
            }
            //加权限控制
            //11总经理
            //13团队经理
            if (!GMLogin.isAdminUser() && !GMLogin.isRole(11) && string.IsNullOrEmpty(teamName) && !isTeamCall)
            {
                if (GMLogin.User.FRealName.IndexOf(",") > 0)
                {
                    sqlUser = sqlUser.and("1=2");
                }
                else
                {
                    sqlUser = sqlUser.and("FRealName=" + GMLogin.User.FRealName.wrap());
                }
            }
            sqlUser += " ORDER BY FRealName ";
            IList listUser = dao.QueryBySql(sqlUser);
            string inStr = "";
            foreach (String realName in listUser)
            {
                if (inStr != "")
                {
                    inStr += ",";
                }
                inStr += "'" + realName + "'";
            }
            if (inStr=="")
            {
                inStr = "-99999";
            }

            //报表数据
            string sqlTemp = @"SELECT FRealName,COUNT(*) fcount FROM c_project_trace
                                WHERE FTalkTime>1 and FType = {0} AND FUserID > 0 and {1} AND FRealName IS NOT NULL AND FRealName in({2})
                                GROUP BY FRealName
                                ORDER BY FRealName";
            string sqlTemp2 = @"SELECT FRealName,COUNT(*) fcount FROM c_report_trace
                                WHERE FType = {0} AND FUserID > 0 and {1} AND FRealName IS NOT NULL AND FRealName in({2})
                                GROUP BY FRealName
                                ORDER BY FRealName";
            string sqlTemp3 = @"SELECT FRealName,sum(FAvailCount),MIN(FNote) fcount FROM c_report_check
                                WHERE {0} AND FRealName IS NOT NULL AND FRealName in({1})
                                GROUP BY FRealName
                                ORDER BY FRealName";
            string where = "1=1".and(Request["where"]);
            //加权限控制
            if (!GMLogin.isAdminUser() && !GMLogin.isRole(11) && string.IsNullOrEmpty(teamName) && !isTeamCall)
            {
                if (GMLogin.User.FRealName.IndexOf(",") > 0)
                {
                    where = where.and("1=2");
                }
                else
                {
                    where = where.and("FRealName=" + GMLogin.User.FRealName.wrap());
                }
            }
            IList list0 = dao.QueryBySql(String.Format(sqlTemp, "0", where, inStr));
            IList list1 = dao.QueryBySql(String.Format(sqlTemp2, "1", where, inStr));
            IList list2 = dao.QueryBySql(String.Format(sqlTemp2, "2", where, inStr));
            IList list3 = dao.QueryBySql(String.Format(sqlTemp2, "3", where, inStr));
            IList list4 = dao.QueryBySql(String.Format(sqlTemp3, where, inStr));
            //合并数据
            int index0 = 0;
            int index1 = 0;
            int index2 = 0;
            int index3 = 0;
            int index4 = 0;
            foreach (String realName in listUser)
            {
                Dictionary<string, object> item = new Dictionary<string, object>();

                item["UserName"] = realName;
                item["Count0"] = 0;
                item["Count1"] = 0;
                item["Count2"] = 0;
                item["Count3"] = 0;
                item["Count4"] = 0;
                item["note"] = "未审核";
                //电话记录
                if (index0 < list0.Count)
                {
                    Object[] obj = (Object[])list0[index0];
                    if (obj[0].ToString() == realName)
                    {
                        item["Count0"] = obj[1];
                        index0++;
                    }
                }
                //新增意向客户
                if (index1 < list1.Count)
                {
                    Object[] obj = (Object[])list1[index1];
                    if (obj[0].ToString() == realName)
                    {
                        item["Count1"] = obj[1];
                        index1++;
                    }
                }
                //新增发合同
                if (index2 < list2.Count)
                {
                    Object[] obj = (Object[])list2[index2];
                    if (obj[0].ToString() == realName)
                    {
                        item["Count2"] = obj[1];
                        index2++;
                    }
                }
                //签单
                if (index3 < list3.Count)
                {
                    Object[] obj = (Object[])list3[index3];
                    if (obj[0].ToString() == realName)
                    {
                        item["Count3"] = obj[1];
                        index3++;
                    }
                }
                //有效电话量
                if (index4 < list4.Count)
                {
                    Object[] obj = (Object[])list4[index4];
                    if (obj[0].ToString() == realName)
                    {
                        item["Count4"] = obj[1];
                        item["note"] = obj[2];
                        index4++;
                    }
                }
                result.Add(item);
            }
            //返回结果
            return result;
        }
    }
}